#include "PhotoBooth.h"



const string PhotoBooth::GAME_IP = "192.168.0.1";
const int PhotoBooth::GAME_PORT = 8765;

const string PhotoBooth::SCOREBOARD_IP = "192.168.0.3";
const int PhotoBooth::SCOREBOARD_PORT = 8775;


void drawTtfStringCentered( ofTrueTypeFont& font, const std::string& s, int x, int y )
{
    //font.drawString( s, x - font.stringWidth( s ) / 2, y + font.stringHeight( s ) / 2 );
    font.drawString( s, x - font.stringWidth( s ) / 2, y);
}



void PhotoBooth::setup()
{
    RGBtoHSV(230,90,67);
    screenWidth = ofGetScreenWidth();
    screenHeight = ofGetScreenHeight();
    playerAmount = 3;
    receiver.setup( PORT );
    mask = 0.35;
    mask2 = 0.65;
    culture2 = 396;

    cancelTime = 5;
    finishedWaitingTime = 8;
    showSnapshotTime = 2.5;

    topleft.x = (screenWidth / 2) - (camWidth / 2);
    topleft.y = (screenHeight / 2) - (camHeight / 2);

    fileManager.startThread();
    ofEnableAlphaBlending();
    vidGrabber.setVerbose(true);
    vidGrabber.initGrabber(camWidth, camHeight);
    franklinBook.loadFont("frabk.ttf", 32);
    franklinBook2.loadFont("frabk.ttf", 15);
    OLDENGL.loadFont("OLDENGL.ttf", 32);
    OLDENGL2.loadFont("OLDENGL.ttf", 15);
    nyala.loadFont("Nyala.ttf", 32);
    nyala2.loadFont("Nyala.ttf", 15);
    nyala3.loadFont("Nyala.ttf", 40);

    counter = cancelTime;
    logo.loadImage("logo.png");
    logoBig.loadImage("logo.png");

    balanceMeter.loadImage("BalanceMeter.png");
    balancePointer.loadImage("BalanceWijzer.png");
    balanceMeterVert.loadImage("BalanceMeterVert.png");
    balanceWijzerHead.loadImage("BalanceWijzerHead.png");
    balanceMeterG.loadImage("BalancetargetGreen.png");
    balanceMeterO.loadImage("BalancetargetOrange.png");
    balanceMeterP.loadImage("BalancetargetPurple.png");

    contourImage.loadImage("Head.png");

    totalPixels = camWidth * camHeight * 4;
    totalPixelsTop = camWidth * camTop * 4;
    totalPixelsBottom = camWidth * camBottom * 4;

    snapshot.allocate(camWidth, camHeight, OF_IMAGE_COLOR_ALPHA);
    snapshotTaken = false;
    Meter = false;
    setState(PhotoBooth::PB_STATE_PLAYERSTATUS);
    balance.setup();
    vgafix.loadFont("vgafix.ttf", 15);
    vgafix2.loadFont("vgafix.ttf", 32);

    topleft2.x = (screenWidth / 2) - (culture2 / 2);
    topleft2.y = (screenHeight / 2) - (160 / 2);

    ofHideCursor();

    startX = 0;
    startY = 220;
    stepY = 50;

    screenCenter = 512;
    screenRight = 1024;


    greenInfo.loadImage("PhotoboothInstructionsGreen.png");
    purpleInfo.loadImage("PhotoboothInstructionsPurple.png");
    orangeInfo.loadImage("PhotoboothInstructionsOrange.png");

    balanceStateWait = -1;

    greenJoystick.loadImage("JoyG.png");
    purpleJoystick.loadImage("JoyP.png");
    orangeJoystick.loadImage("JoyO.png");

    logo.resize((3543/10),(1329/10));
    logoBig.resize((3543/6),(1329/6));
}


void PhotoBooth::update()
{

    vidGrabber.grabFrame();
    balance.update();
    meterValue();
    setMasks();

}

void PhotoBooth::draw()
{

    ofSetColor(255,255,255);
    states();

}

/*
Here the color layers are being made.
*/
void PhotoBooth::setMasks()
{

    if(playerAmount == 3)
    {
        player = 1;
        maskR = mask * 84;
        maskG = mask * 255;
        maskB = mask * 0;

    }
    if(playerAmount == 2)
    {
        player = 2;
        maskR = mask * 255;
        maskG = mask * 0;
        maskB = mask * 253;
    }
    if(playerAmount == 1)
    {
        player = 3;
        maskR = mask * 255;
        maskG = mask * 152;
        maskB = mask * 8;
    }
    balance.setPlayer(player);

}

void PhotoBooth::states()
{

    switch(getState())
    {

    case(PhotoBooth::PB_STATE_PLAYERSTATUS):
        ofSetColor(255,255,255);

        logo.draw(topleft.x+150,0);

        if(playerAmount != 0)
        {
            setState(PhotoBooth::PB_STATE_INSTRUCT);
        }

        else
        {
            char charArr[255];

            sprintf(charArr, "Please wait for players to finish", counter);

            nyala.drawString(charArr, topleft.x + 50, topleft.y + 50);
            receiveMessage();
        }


        break;

    case(PhotoBooth::PB_STATE_INSTRUCT):
        ofSetColor(255,255,255);

        logoBig.draw(screenCenter - logoBig.width/2,0);

        ofSetColor(255,209,20);
        drawTtfStringCentered(nyala3,"Welcome to the game",screenCenter, startY + stepY*0.5);
        ofSetColor(255,255,255);
        drawTtfStringCentered(nyala,"Steps to take:", screenCenter,startY + stepY*2.5);
        drawTtfStringCentered(nyala,"1. Choose your balance", screenCenter,startY + stepY*4);
        drawTtfStringCentered(nyala,"2. Take your picture", screenCenter,startY + stepY*5);
        drawTtfStringCentered(nyala,"3. Walk to your joystick", screenCenter,startY + stepY*6);
        ofSetColor(124,185,255);
        drawTtfStringCentered(nyala,"Press the button when you are ready to start", screenCenter,startY + stepY*10);
        ofSetColor(255,255,255);


        break;


    case(PhotoBooth::PB_STATE_TAKEPICTURE):
        logo.resize((3543/10),(1329/10));
        logo.draw(topleft.x+150,0);
        ofSetColor(255,209,20);
        drawTtfStringCentered(nyala3,"Step  ", screenCenter - 40,startY-stepY*1.5);

        ofSetColor(124,185,255);


        drawTtfStringCentered(nyala3,"2/3", screenCenter + 50,startY-stepY*1.5);

        ofSetColor(255,255,255);

        vidGrabber.draw(topleft.x,topleft.y+100);
        pictureSaved = false;



        //contourImage.draw(topleft.x + 80, topleft.y+100-20, 540, 500);
        ofLine(topleft.x, topleft.y+100 + camTop, topleft.x + camWidth, topleft.y+100 + camTop);
        if(player == 1)
        {
            ofSetColor(84,255,0);
            char charArr3[255];
            sprintf(charArr3, "Player : %i", player);
            drawTtfStringCentered(nyala, charArr3, screenCenter,startY-stepY*0.7);
        }

        if(player == 2)
        {
            ofSetColor(255,0,253);
            char charArr3[255];
            sprintf(charArr3, "Player : %i", player);
            drawTtfStringCentered(nyala, charArr3, screenCenter,startY-stepY*0.7);
        }
        if(player == 3)
        {
            ofSetColor(255,152,8);
            char charArr3[255];
            sprintf(charArr3, "Player : %i", player);
            drawTtfStringCentered(nyala, charArr3, screenCenter,startY-stepY*0.7);
        }
        ofSetColor(255,255,255);
        drawTtfStringCentered(nyala,"Position your head and press the button", screenCenter,startY+stepY*0.3);

        ofSetColor(255,255,255);
        break;


        /*  case(PhotoBooth::PB_STATE_VIEWHEAD):
               chromaKeyHSV();
               topSnapshot.draw(topleft.x, topleft.y+100);
               bottomSnapshot.draw(topleft.x,topleft.y + camTop+100);
               char charArr[255];


               sprintf(charArr, "Sending picture, press button to cancel and retry: %i", counter);
               nyala.drawString(charArr, topleft.x - 100-10, topleft.y + 30);
               ofSetColor(255,209,20);
               nyala.drawString("Step", topleft.x,topleft.y-20);
               ofSetColor(124,185,255);
               nyala.drawString("     2/3", topleft.x,topleft.y-20);

               if(player == 1)
               {
                   ofSetColor(84,255,0);
                   char charArr3[255];
                   sprintf(charArr3, "Player : %i", player);
                   nyala.drawString(charArr3, topleft.x+camWidth-160,topleft.y-20);
               }

               if(player == 2)
               {
                   ofSetColor(255,0,253);
                   char charArr3[255];
                   sprintf(charArr3, "Player : %i", player);
                   nyala.drawString(charArr3, topleft.x+camWidth-160,topleft.y-20);
               }
               if(player == 3)
               {
                   ofSetColor(255,152,8);
                   char charArr3[255];
                   sprintf(charArr3, "Player : %i", player);
                   nyala.drawString(charArr3, topleft.x+camWidth-160,topleft.y-20);
               }
               ofSetColor(255,255,255);

               if(getTime <= ofGetElapsedTimeMillis())
               {
                   counter--;
                   getTime = ofGetElapsedTimeMillis() + 1000;
               }

               if(counter == -1)
               {
                   snapshotTaken = false;
                   Meter = true;
                   counter = cancelTime;
                   chromaKeyHSV();
                   setState(PhotoBooth::PB_STATE_METER);
               }

               break;
                */

    case(PhotoBooth::PB_STATE_METER):
        logo.resize((3543/10),(1329/10));
        logo.draw(topleft.x+150,0);

        balance.draw();

        break;

    case(PhotoBooth::PB_STATE_FINISHED):
        logo.resize((3543/10),(1329/10));
        logo.draw(topleft.x+150,0);
        if(getTime2 >= ofGetElapsedTimeMillis())
        {
            if(player == 1)
            {
                ofSetColor(84,255,0);

                drawTtfStringCentered(nyala,"Walk to the green joystick and wait for countdown", screenCenter,startY - stepY*0.5);
                ofSetColor(255,255,255);
                // greenInfo.draw(0,100);
                greenJoystick.draw(screenCenter - purpleJoystick.width/2, 200);
                ofSetColor(255,255,255);
            }

            if(player == 2)
            {
                ofSetColor(255,0,253);

                drawTtfStringCentered(nyala,"Walk to the purple joystick and wait for countdown", screenCenter,startY - stepY*0.5);
                ofSetColor(255,255,255);
                //purpleInfo.draw(0,100);
                purpleJoystick.draw(screenCenter - purpleJoystick.width/2, 200);
                ofSetColor(255,255,255);
            }
            if(player == 3)
            {
                ofSetColor(255,152,8);
                drawTtfStringCentered(nyala,"Walk to the orange joystick and wait for countdown", screenCenter,startY - stepY*0.5);
                ofSetColor(255,255,255);
                //orangeInfo.draw(0,100);
                orangeJoystick.draw(screenCenter - purpleJoystick.width/2, 200);
                ofSetColor(255,255,255);
            }
        }
        else if(playerAmount!=0)
        {
            playerAmount--;
            setState(PhotoBooth::PB_STATE_INSTRUCT);
        }
        if(playerAmount==0)
        {
            setState(PhotoBooth::PB_STATE_PLAYERSTATUS);
        }
        if(pictureSaved != true)
        {
            setDateName();
            saveSnapshotImages();
            string localFileTop = dateNameTop;
            string localFileBottom = dateNameBottom;
            string remoteFileTop = dateNameTop;
            string remoteFileBottom = dateNameBottom;
            fileManager.transferFile( GAME_IP, ofToString( GAME_PORT ), "Pictureshots/" + localFileTop, "player-images/" + remoteFileTop );
            fileManager.transferFile( GAME_IP, ofToString( GAME_PORT ), "Pictureshots/" + localFileBottom, "player-images/" + remoteFileBottom );
            fileManager.transferFile( SCOREBOARD_IP, ofToString( SCOREBOARD_PORT ), "Pictureshots/" + localFileTop, "player-images/" + remoteFileTop );
            fileManager.transferFile( SCOREBOARD_IP, ofToString( SCOREBOARD_PORT ), "Pictureshots/" + localFileBottom, "player-images/" + remoteFileBottom );
            pictureSaved = true;
        }
        ofSetColor(255,255,255);
        break;

    case(PhotoBooth::PB_STATE_SHOWSNAPSHOT):
        topSnapshot.draw(topleft.x, topleft.y+100);
        bottomSnapshot.draw(topleft.x,topleft.y + camTop+100);
        ofSetColor(255,255,255);
        drawTtfStringCentered(nyala,"Picture taken...", screenCenter,startY+stepY*0.3);
        logo.draw(topleft.x+150,0);
        if(getTime <= ofGetElapsedTimeMillis())
        {

            setState(PhotoBooth::PB_STATE_FINISHED);
            getTime2 = ofGetElapsedTimeMillis() + (finishedWaitingTime*1000);

        }
    }



}



void PhotoBooth::eventReceived()
{


}

void PhotoBooth::updateSnapshot()
{


}

/*
OSC message receiving
*/
void PhotoBooth::receiveMessage()
{


    // hide old messages
    for ( int i=0; i<NUM_MSG_STRINGS; i++ )
    {
        if ( timers[i] < ofGetElapsedTimef() )
            msg_strings[i] = "";
    }

    // check for waiting messages
    if( receiver.hasWaitingMessages() )
    {
        // get the next message
        ofxOscMessage m;
        receiver.getNextMessage( &m );

        // check for mouse moved message
        if ( m.getAddress() == "/mouse/position" )
        {

        }


        else
        {
            // unrecognized message: display on the bottom of the screen
            string msg_string;
            msg_string = m.getAddress();
            msg_string += ": ";
            for ( int i=0; i<m.getNumArgs(); i++ )
            {
                // get the argument type
                msg_string += m.getArgTypeName( i );
                msg_string += ":";
                // display the argument - make sure we get the right type
                if( m.getArgType( i ) == OFXOSC_TYPE_INT32 )
                    msg_string += ofToString( m.getArgAsInt32( i ) );
                else if( m.getArgType( i ) == OFXOSC_TYPE_FLOAT )
                    msg_string += ofToString( m.getArgAsFloat( i ) );
                else if( m.getArgType( i ) == OFXOSC_TYPE_STRING )
                    msg_string += m.getArgAsString( i );
                else
                    msg_string += "unknown";
            }
            // add to the list of strings to display
            msg_strings[current_msg_string] = msg_string;
            timers[current_msg_string] = ofGetElapsedTimef() + 5.0f;
            current_msg_string = ( current_msg_string + 1 ) % NUM_MSG_STRINGS;
            // clear the next line
            msg_strings[current_msg_string] = "";
        }
        cout << m.getArgAsString(0) << endl;
        if(m.getArgAsString(0)== "sendNewPlayers")
        {

            playerAmount = 3;

        }
    }

}

/*
Filtering the greenscreen with rgb colors.


*/
void PhotoBooth::chromaKey()
{


    snapshot.setImageType(OF_IMAGE_COLOR_ALPHA);
    snapshotPixels = snapshot.getPixels();

    for (int i = 0; i < totalPixels; i += 4)
    {

        if(i <= camWidth * camHeight * 4)
        {
            RGBtoHSV(snapshotPixels[i],snapshotPixels[i+1],snapshotPixels[i+2]);

            if(snapshotPixels[i]>100&&snapshotPixels[i]<190&&
                    snapshotPixels[i+1]>245&&snapshotPixels[i+1]<256&&
                    snapshotPixels[i+2]>135&&snapshotPixels[i+2]<215)
            {

                topPixels[i] = 255;
                topPixels[i + 1] = 255;
                topPixels[i + 2] = 255;
                topPixels[i + 3] = 0;

            }
            else
            {
                topPixels[i] = snapshotPixels[i];
                topPixels[i + 1] = snapshotPixels[i + 1];
                topPixels[i + 2] = snapshotPixels[i + 2];
                topPixels[i + 3] = 255;
            }

        }

        if (i >= camWidth * camTop * 4)
        {

            if(snapshotPixels[i]>100&&snapshotPixels[i]<190&&
                    snapshotPixels[i+1]>245&&snapshotPixels[i+1]<256&&
                    snapshotPixels[i+2]>135&&snapshotPixels[i+2]<215)
            {

                bottomPixels[i - totalPixelsTop] = 255;
                bottomPixels[i + 1 - totalPixelsTop] = 255;
                bottomPixels[i + 2 - totalPixelsTop] = 255;
                bottomPixels[i + 3 - totalPixelsTop] = 0;

            }
            else
            {
                bottomPixels[i - totalPixelsTop] = snapshotPixels[i];
                bottomPixels[i + 1 - totalPixelsTop] = snapshotPixels[i + 1];
                bottomPixels[i + 2 - totalPixelsTop] = snapshotPixels[i + 2];
                bottomPixels[i + 3 - totalPixelsTop] = 255;
            }
        }
    }



    topSnapshot.setFromPixels(topPixels, camWidth, camTop, OF_IMAGE_COLOR_ALPHA);
    bottomSnapshot.setFromPixels(bottomPixels, camWidth, camBottom, OF_IMAGE_COLOR_ALPHA);


}

/*
Filtering the greenscreen with RGB to HSV color convertion

*/

void PhotoBooth::chromaKeyHSV()
{
    snapshot.setImageType(OF_IMAGE_COLOR_ALPHA);
    snapshotPixels = snapshot.getPixels();

    for (int i = 0; i < totalPixels; i += 4)
    {
        if(i <= camWidth * camHeight * 4)
        {
            RGBtoHSV(snapshotPixels[i],snapshotPixels[i+1],snapshotPixels[i+2]);

            if(h > 50 && h < 100 &&
                    s > 0.25 && s <= 1.00 &&
                    v > 70 && v < 190)
            {

                topPixels[i] = 255;
                topPixels[i + 1] = 255;
                topPixels[i + 2] = 255;
                topPixels[i + 3] = 0;

            }
            else
            {
                topPixels[i] = (snapshotPixels[i]*mask2)+maskR;
                topPixels[i + 1] = (snapshotPixels[i + 1]*mask2)+maskG;
                topPixels[i + 2] = (snapshotPixels[i + 2]*mask2)+maskB;
                topPixels[i + 3] = 255;
            }

        }

        if (i >= camWidth * camTop * 4)
        {

            if(h > 50 && h < 100 &&
                    s > 0.25 && s <= 1.00 &&
                    v > 70 && v < 190)
            {

                bottomPixels[i - totalPixelsTop] = 255;
                bottomPixels[i + 1 - totalPixelsTop] = 255;
                bottomPixels[i + 2 - totalPixelsTop] = 255;
                bottomPixels[i + 3 - totalPixelsTop] = 0;

            }
            else
            {
                bottomPixels[i - totalPixelsTop] = (snapshotPixels[i]*mask2)+maskR;
                bottomPixels[i + 1 - totalPixelsTop] = (snapshotPixels[i + 1]*mask2)+maskG;
                bottomPixels[i + 2 - totalPixelsTop] = (snapshotPixels[i + 2]*mask2)+maskB;
                bottomPixels[i + 3 - totalPixelsTop] = 255;
            }
        }
    }
    for(int y = 0; y < camHeight ; y++ )
    {
        topPixels[(y * camWidth) * 4 + 3] = 0;
        topPixels[(y * camWidth + 1) * 4 + 3] = 0;
        topPixels[(y * camWidth + (camWidth-1)) * 4 + 3] = 0;
        topPixels[(y * camWidth + (camWidth-2)) * 4 + 3] = 0;
        bottomPixels[(y * camWidth) * 4 + 3] = 0;
        bottomPixels[(y * camWidth + 1) * 4 + 3] = 0;
        bottomPixels[(y * camWidth + (camWidth-1)) * 4 + 3] = 0;
        bottomPixels[(y * camWidth + (camWidth-2)) * 4 + 3] = 0;
    }

    for(int x = 0; x < camWidth ; x++ )
    {
        topPixels[(0 * camWidth + x) * 4 + 3] = 0;
        topPixels[(1 * camWidth + x) * 4 + 3] = 0;

        bottomPixels[((camBottom - 2) * camWidth + x) * 4 + 3] = 0;
        bottomPixels[((camBottom - 1) * camWidth + x) * 4 + 3] = 0;
        //  bottomPixels[((camBottom) * camWidth + x) * 4 + 3] = 0;
    }


    topSnapshot.setFromPixels(topPixels, camWidth, camTop, OF_IMAGE_COLOR_ALPHA);
    bottomSnapshot.setFromPixels(bottomPixels, camWidth, camBottom, OF_IMAGE_COLOR_ALPHA);


}

/*
Filtered and splitted pictures are being saved to a file, and can be resized before saving.

*/
void PhotoBooth::saveSnapshotImages()
{


#ifdef ENABLE_RESIZING
    topSnapshot.resize(60,42);
    bottomSnapshot.resize(60,17);
#endif

    topSnapshot.saveImage("Pictureshots/" + dateNameTop);
    bottomSnapshot.saveImage("Pictureshots/" + dateNameBottom);

}


/*
The big red button gives an 'a' as input. So all the user input is a keypressed 'a'.

*/
void PhotoBooth::keyPressed(int key)
{

    if(getState()==PB_STATE_INSTRUCT)
    {
        if(key == 'a' || key == 'A')
        {
            //Sleep(1000);
            key = 0;
            balanceStateWait = ofGetElapsedTimeMillis() + 500;
            setState(PhotoBooth::PB_STATE_METER);
        }
    }

    if(getState()==PB_STATE_METER)
    {
        if(balanceStateWait <= ofGetElapsedTimeMillis())
        {
            balance.keyPressed(key);
            balanceStateWait = -1;
        }
    }

    if(getState()==PB_STATE_TAKEPICTURE)
    {
        if (key == 'a' || key == 'A')
        {
            key = 0;
            framePixels = vidGrabber.getPixels();
            snapshot.setFromPixels(framePixels, camWidth, camHeight, OF_IMAGE_COLOR);

            snapshotTaken = true;
            getTime = ofGetElapsedTimeMillis() + 1000 * showSnapshotTime;

            chromaKeyHSV();

            //cout<<"snapshot"<<endl;
            setState(PhotoBooth::PB_STATE_SHOWSNAPSHOT);
        }

    }





    /*   if(getState()==PB_STATE_CONFIRM)
       {
           if (key == 'a')
           {
               key = NULL;
               setState(PhotoBooth::PB_STATE_TAKEPICTURE);
               if(snapshotTaken == true)
               {
                   counter = cancelTime;
                   snapshotTaken = false;
               }
           }
       }
       */
    if(key== 'f' || key == 'F')
    {
        ofToggleFullscreen();
    }


}

/*
For unique file names the files get a date in month/day/hour/minute/second
and a culture/industry value, with at the end a mark for being a top or bottom image.
Everything has two numbers, except for the culture/insustry value wich has three.
*/
void PhotoBooth::setDateName()
{
    iPercentage = round(iPercentage / 5)*5;
    cPercentage = 100 - iPercentage;
    int month = ofGetMonth();
    int day = ofGetDay();
    int hour = ofGetHours();
    int minutes = ofGetMinutes();
    int seconds = ofGetSeconds();

    Month = toPaddedString(month, 2);
    Day = toPaddedString(day, 2);
    Hour = toPaddedString(hour, 2);
    Minute = toPaddedString(minutes, 2);
    Second = toPaddedString(seconds, 2);
    Culture = toPaddedString(cPercentage, 3);
    Industry = toPaddedString(iPercentage,3);
    Player = ofToString(player);

    dateNameTop = Month + "-" + Day + "-" + Hour + "-" + Minute + "-" + Second
                  + "-" + Culture + "-" + Industry + "-" + Player + "_Top.png";
    dateNameBottom = Month + "-" + Day + "-" + Hour + "-" + Minute + "-" + Second
                     + "-" + Culture + "-" + Industry + "-" + Player + "_Bottom.png";

    cout << dateNameTop << endl << dateNameBottom << endl;



}

string PhotoBooth::toPaddedString(double value, int padLength)
{
    stringstream sstr;
    sstr  << setw(padLength) << setfill('0') << value;
    return sstr.str();
}

void PhotoBooth::setState(PB_STATE newState)
{

    pbState = newState;

}

PhotoBooth::PB_STATE PhotoBooth::getState()
{

    return pbState;

}

int PhotoBooth::meterValue()
{
    if(balance.isMeterSet() == true)
    {
        culture = balance.getCultureValue();
        industry = balance.getIndustryValue();
        cPercentage = balance.getcPercentage();
        iPercentage = balance.getiPercentage();
        cout << culture << " " << industry << endl;
        Sleep(2000);
        //getTime2 = ofGetElapsedTimeMillis() + (finishedWaitingTime*1000);
        setState(PhotoBooth::PB_STATE_TAKEPICTURE);
        balance.stop = false;

    }


}

void PhotoBooth::redrawMeter()
{
    balanceMeterVert.draw(topleft2.x+120,topleft2.y-50);

    ofSetColor(255,255,255);
    //nyala2.drawString("Press button to set your goal", topleft2.x, topleft2.y+400);
    if(player == 1)
    {
        balanceMeterG.draw(topleft2.x+135,topleft2.y-50+industry-8);
        nyala.drawString("You can now start playing",  topleft.x + 100, topleft.y + 30);
        ofSetColor(84,255,0);
        nyala.drawString("Go to the green joystick and wait for you turn",  topleft.x -60, topleft.y + 80);

    }
    if(player == 2)
    {
        balanceMeterP.draw(topleft2.x+135,topleft2.y-50+industry-8);
        nyala.drawString("You can now start playing",  topleft.x+ 100, topleft.y + 30);
        ofSetColor(255,0,253);
        nyala.drawString("Go to the purple joystick and wait for you turn",  topleft.x - 60, topleft.y + 80);

    }
    if(player == 3)
    {
        balanceMeterO.draw(topleft2.x+135,topleft2.y-50+industry-8);
        nyala.drawString("You can now start playing",  topleft.x+ 100, topleft.y + 30);
        ofSetColor(255,152,8);
        nyala.drawString("Go to the orange joystick and wait for you turn",  topleft.x-60, topleft.y + 80);

    }
    char fpsStr[255];
    char fpsStr2[255];
    sprintf(fpsStr, "%i", cPercentage);
    sprintf(fpsStr2, "%i", iPercentage);
    ofSetColor(255,209,20);
    OLDENGL2.drawString(fpsStr, topleft2.x+95, topleft2.y-35+industry);
    ofSetColor(124,185,255);
    vgafix.drawString(fpsStr2, topleft2.x+278, topleft2.y-35 +industry);
    ofSetColor(255,255,255);
    /*
        ofSetColor(255,255,255);
        nyala.drawString("This is your goal:", topleft2.x, topleft2.y - 50);
        ofSetColor(255,255,255);
        nyala.drawString("Thank you and have fun!!!", topleft2.x, topleft2.y + 220);
        char charArr2[255];
        sprintf(charArr2, "Player : %i", player);
        nyala.drawString(charArr2, topleft2.x,200);
    */


}

/*
Color conversion from RBG to HSV.

*/
void PhotoBooth::RGBtoHSV( float r, float g, float b)

{
    float min, max;
    float delta;

    min = MINRGB( r, g, b );
    max = MAXRGB( r, g, b );
    v = max;				// v

    delta = max - min;

    if( max != 0 )
        s = delta / max;		// s
    else
    {
        // r = g = b = 0		// s = 0, v is undefined
        s = 0;
        h = -1;
        return;
    }
    if(delta != 0)
    {
        if( r == max )
            h = ( g - b ) / delta;		// between yellow & magenta
        else if( g == max )
            h = 2 + ( b - r ) / delta;	// between cyan & yellow
        else
            h = 4 + ( r - g ) / delta;	// between magenta & cyan
    }
    else
    {
        h = 0;
    }
    h *= 60;				// degrees
    if( h < 0 )
        h += 360;

//cout << h << " " << s << " " << v << endl;
//printf("%.2f %.2f %.2f -> %.2f %.2f %.2f\n",r,g,b,h,s,v);
}

float PhotoBooth::MINRGB(float r, float g, float b)
{

    if(r<g && r<b)
    {
        return r;
    }
    if(g<r && g<b)
    {
        return g;
    }
    if(b<r && b<g)
    {
        return b;
    }
    return r;
}

float PhotoBooth::MAXRGB(float r,float g, float b)
{
    if(r>g && r>b)
    {
        return r;
    }
    if(g>r && g>b)
    {
        return g;
    }
    if(b>r && b>g)
    {
        return b;
    }
    return r;

}

